```{r}
#| label: exampleCode1
#| lst-label: lst-exampleChunk
#| lst-cap: "Formatting a Code Chunk for R"
#| eval: false
# A First Example Code Chunk ---
1 + 1
```2 Coding in Quarto
There are two ways that you can use programming languages in Quarto documents. You can run (simple) commands inline or you can write code chunks.
2.1 Inline Code
Inline code is great for reporting a value that you have stored in the environment, to do a quick calculation, or something else that is simple. To create some inline code, you’ll need to start with a backtick (or grave), `, the symbol located on the key just to the left of the 1 key. This will start your code; you’ll close the code with another instance of the backtick, `. You’ll need to type a lower case r right after the first backtick to state what language your code is supposed to be (in this case R). For example, ` r 1 + 2 ` will yield 3. Notice that inline code is evaluated and the result is displayed.
Inline code will automatically be run when you render the document.
2.2 Code Chunks
Code chunks are much larger blocks where you can do more complicated things. For example, you can use code chunks to import a picture, load and clean data, create data visualizations, tables, and run models, etc.
You can add a code chunk manually by typing three backticks in a row on new line. When you’re finished with the chunk, you type another three backticks. In the first line, just after the three backticks, you need to include a set of curly braces and list the programming language for the code. For instance {r}. All of your code should be on lines in between these two lines as well as any chunk options. Listing 2.1 shows how you should set up a code chunk for R in a Quarto document. In RStudio Desktop, you can also use the insert code chunk button (looks like a green square with a plus sign and the letter C) and select R to get a code chunk. Alternatively you can also use the keyboard shortcut Command + Option + i (Mac) or Ctrl + Alt + i (Windows).
The four lines that start with #| list out the code chunk options. These follow the YAML structure of key: value. These code chunk options allow you to grant format exceptions from default as well as configure figure size, captions, and position.
eval and include Keys
Be cautious of the eval and include keys. The eval key controls whether or not the code chunk will run during rendering; the include key controls whether the output of the code will get included in the rendered document (the code still runs).
You can execute (run) code chunks individually by clicking the play button located in the upper-right corner of each chunk. This will display the output of the code in a collapsible window below the chunk. Keep in mind that when you run code this way, it references your current environment for items.
When you render a Quarto document, R will create a new environment that is separate from your local environment and run all of the code fresh. The results of that run will be what get put into the output file(s).
A common issue students run into when working with Quarto is forgetting that rendering creates a new environment. They will often load data to their local environment but not have any code in their Quarto document that loads the data. Thus, when they render their Quarto file, their code fails as objects are missing.
Code chunks can be run individually by clicking the play button located in the upper right corner of each chunk. This should display the output of the code chunk in a collapsible window below the code. All code chunks will run when you knit/render the document unless you’ve specified otherwise as a chunk option.
A best practice to follow when working with Quarto documents is to make each code chunk dedicated to ONE task. That is, each code chunk is really only meant to cover one thing. For example, one code chunk should be used to load all of your needed packages and set global options. A second code chunk should load your data, while a third deals with any particular cleaning. Each data visualization (plots, graphs, and tables) should get their own chunk.
2.2.1 Formating Your Code Chunks
When setting up a code chunk, there are some steps you should take to ensure that your code chunk is in good shape.
- Leave an empty line before and after you make the code chunk. That is, there should be an empty line your QMD file immediately before and after the opening and closing set of three backticks (i.e., ```).
- Immediately after the opening three backticks, you need to specify the language of the code chunk in a set of curly braces. For example,
```{r}. - Code chunk options should be listed at the top of the code chunk. There should be no empty lines between the start of the code chunk and the chunk options.
- Each code chunk option gets its own line and should begin with
#|. There should be a single space between the vertical pipe symbol and the first letter of the option key. - Code chunk options are essentially YAML
key: valuepairs. - The
labelfor a code chunk should be unique (no duplicates allowed in the document). Avoid using underscores in the label value. See Chapter 6 for additional information. - Leave an empty line between your last code chunk option and the start of your code.
- Use code comments to help structure your code. These will become invaluable when someone looks at your Code Appendix.
- Leave an empty space between your last line of code and the closing three backticks. This will help create spacing for your Code Appendix.
2.3 Using Multiple Coding Languages
One of the powerful aspects of Quarto documents is that they support multiple programming languages within the same document. Currently, Quarto supports R, Python, Julia, and Observable JavaScript for computations. Quarto also understands HTML, YAML, CSS, and SQL (via the {knitr} R package).
Keep in mind that if you are going to use multiple programming languages in the same document, you must have the appropriate engines installed on your machine. That is, you need to have a Python installation if you plan to run Python code; R if you plan to run R code, etc.
For Python, you’ll need to install the jupyter package. For details, check out the Using Python page of Quarto (Using Python, n.d.). You will also need to add the key: value pair jupyter: python3 to your YAML header or to the code chunk as shown in Listing 2.2.
Listing 2.2 shows an example code chunk that uses Python instead of R with in the Quarto document that makes this webpage.
```{python}
#| jupyter: python3
#| lst-label: lst-python
#| lst-cap: "An example of a python code chunk"
# An example python code chunk ----
prefix = "Stat"
num = 184
statement = "Welcome to {} {}!".format(prefix, num)
print(statement)
```Welcome to Stat 184!
One of the most powerful aspects of a multi-programming language document is that you can use different languages for different tasks, playing to the strengths of the tasks. In Quarto, you can pass variables between Python and R. When rendering your Quarto document to objects will get created: py and r. The py object contains all of your Python variables while r contains all of your R variables. This means that you can access and change elements using the appropriate extractor operator: $ in R and . in Python.
Keep in mind that you still need to have all of the packages you need already installed for all programming languages you are using in a Quarto document. Additionally, there may still be instances where communication errors occur. Get in the habit of regularly testing and rendering the full document.
```{r}
#| lst-label: lst-py2R
#| lst-cap: "Calling a Python Object in R Code Chunk"
# Example of Call Python object in R Chunk ----
library(reticulate)
capStatement <- stringr::str_to_upper(py$statement)
print(capStatement)
# Create new R objects for next example ----
mainPart <- runif(n = 5, min = 50, max = 80)
errorPart <- rnorm(n = 5, mean = 0, sd = 1)
```[1] "WELCOME TO STAT 184!"
In Listing 2.3, you’ll notice that we needed to load the {reticulate} R package. This package needs to be loaded just once in your Quarto document to facilitate passing objects between the two languages.
```{python}
#| jupyter: python3
#| lst-label: lst-R2py
#| lst-cap: "Calling R Objects in Python Code Chunk"
# Example of Calling R objects in Python ----
newValues = [sum(x) for x in zip(r.mainPart, r.errorPart)]
roundedValues = [round(x, 3) for x in newValues]
print(roundedValues)
```[73.8, 61.214, 53.785, 56.772, 74.828]
Similarly, we can access and work with R objects in Python chunks (see Listing 2.4).